import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhouliangliang5
 * @date : 2023/3/15 14:05
 * @description :  teamId length + teamId + randomStr +  "算法int值" + "1";
 */
@Slf4j
public class ConfoundParser  {

    private final Map<Character, String> decodeTable = new HashMap<Character, String>(){
        {
            put('x', "0");
            put('O', "1");
            put('A', "2");
            put('K', "3");
            put('t', "4");
            put('n', "5");
        }
    };


    public String parseTeamId(String appKey) {
        try {
            StringBuilder builder = new StringBuilder(appKey);
            appKey = builder.reverse().toString();
            int length = Integer.valueOf(appKey.substring(0,2));

            String teamId = appKey.substring(2, length + 2);
            teamId = codeTeamId(teamId, decodeTable);
            return teamId;
        } catch (Exception e) {
            //发生异常时返回空
            log.error("ConfoundParser.parseTeamId error " + e.getMessage(), e);
            return "";
        }
    }


    public Integer parseAppType(String appKey) {
        System.out.println(String.valueOf(appKey.charAt(0)));
        return Integer.valueOf(String.valueOf(appKey.charAt(0)));
    }


    public Integer algorithm() {
        return 1;
    }

    /**
     * 根据码表编码 | 解码teamId
     * @return
     */
    private String codeTeamId(String teamId, Map<Character, String> codeTable) {
        StringBuilder builder = new StringBuilder();

        for(int i=0; i<teamId.length(); i++) {
            Character ch = teamId.charAt(i);
            String value = codeTable.get(ch);
            if(StringUtils.isNotEmpty(value)) {
                builder.append(value);
                continue;
            }
            builder.append(ch);
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        Integer appType = new ConfoundParser().parseAppType("1156qhf35qkm6k5xAKAOnKtx7t968tK9nO91");
        String teamId = new ConfoundParser().parseTeamId("1156qhf35qkm6k5xAKAOnKtx7t968tK9nO91");

        System.out.println("appType : " + appType);
        System.out.println(teamId);

    }
}
